package org.luckyjourney.service.booking.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.luckyjourney.config.QiNiuConfig;
import org.luckyjourney.entity.File;
import org.luckyjourney.entity.booking.Booking;
import org.luckyjourney.entity.booking.Orders;
import org.luckyjourney.entity.booking.PsychologicalAppointmentRecords;
import org.luckyjourney.entity.booking.dto.BookingDTO;
import org.luckyjourney.entity.booking.vo.BookingVO;
import org.luckyjourney.entity.booking.vo.OrderVO;
import org.luckyjourney.entity.plan.Plan;
import org.luckyjourney.entity.plan.dto.PlanDTO;
import org.luckyjourney.entity.plan.vo.PlanVO;
import org.luckyjourney.exception.BaseException;
import org.luckyjourney.mapper.booking.BookingMapper;
import org.luckyjourney.mapper.booking.OrdersMapper;
import org.luckyjourney.mapper.booking.PsychologicalAppointmentRecordsMapper;
import org.luckyjourney.service.FileService;
import org.luckyjourney.service.booking.BookingService;
import org.luckyjourney.util.BaseContext;
import org.luckyjourney.util.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BookingServiceImpl implements BookingService {

    @Autowired
    BookingMapper bookingMapper;
    @Autowired
    PsychologicalAppointmentRecordsMapper recordsMapper;

    @Autowired
    private FileService fileService;
    @Autowired
    OrdersMapper ordersMapper;

    @Override
    public List<PlanVO> selectPlan(PlanDTO planDTO) {
        if (ObjectUtil.isEmpty(planDTO.getUserId())) {
            throw new BaseException("请选择要预约的咨询师");
        }
        if (ObjectUtil.isEmpty(planDTO.getPlanDate())) {
            throw new BaseException("请选择要预约的时间段");
        }
        List<PlanVO> planVOS = bookingMapper.selectPlan(planDTO);
        // 创建一个SimpleDateFormat对象，用于格式化时间
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前以后的时间
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 获取系统当前时间
        LocalDate date = LocalDate.now().minusDays(1);
        // String format = sdf.format(date);
        //查询出当前时间以后的数据
        String format = date.format(fmt);
        planDTO.setCreatebeginTime(format);
        Long count=bookingMapper.selectCount(planDTO);

        ArrayList<PlanVO> planVOS1 = new ArrayList<>();
        if (planVOS != null && planVOS.size() > 0) {
            for (PlanVO planVO : planVOS) {
                //咨询的类型
                Long classifyId = planVO.getClassifyId();
                PlanVO planVO1 = new PlanVO();
                if (ObjectUtil.isEmpty(classifyId)) {
                    planVO1.setDisable(true);
                    planVO1.setId(planVO.getId());
                    planVO1.setUserId(planVO.getUserId());
                    planVO1.setCreateTime(planVO.getCreateTime());
                    planVO1.setUpdateTime(planVO.getUpdateTime());
                    planVO1.setPlanDate(planVO.getPlanDate());
                    planVO1.setPlanTime(planVO.getPlanTime());
                    planVO1.setNikeName(planVO.getNikeName());
                    planVO1.setPrice(planVO.getPrice());
                    planVO1.setClassifyName(planVO.getClassifyName());
                    planVO1.setNumberAppointments(planVO.getNumberAppointments());
                } else if (ObjectUtil.isNotEmpty(classifyId) && planVO.getNumberAppointments() == 0 && ObjectUtil.isNotEmpty(planVO.getNumberAppointments())) {
                    planVO1.setFull(false);
                    planVO1.setId(planVO.getId());
                    planVO1.setClassifyId(planVO.getClassifyId());
                    planVO1.setUserId(planVO.getUserId());
                    planVO1.setCreateTime(planVO.getCreateTime());
                    planVO1.setUpdateTime(planVO.getUpdateTime());
                    planVO1.setPlanDate(planVO.getPlanDate());
                    planVO1.setPlanTime(planVO.getPlanTime());
                    planVO1.setNikeName(planVO.getNikeName());
                    planVO1.setPrice(planVO.getPrice());
                    planVO1.setType("face_to_face");
                    planVO1.setClassifyName(planVO.getClassifyName());

                    planVO1.setNumberAppointments(planVO.getNumberAppointments());
                } else {
                    planVO1.setDisable(false);
                    planVO1.setId(planVO.getId());
                    planVO1.setClassifyId(planVO.getClassifyId());
                    planVO1.setUserId(planVO.getUserId());
                    planVO1.setCreateTime(planVO.getCreateTime());
                    planVO1.setUpdateTime(planVO.getUpdateTime());
                    planVO1.setPlanDate(planVO.getPlanDate());
                    planVO1.setPlanTime(planVO.getPlanTime());
                    planVO1.setNikeName(planVO.getNikeName());
                    planVO1.setPrice(planVO.getPrice());
                    planVO1.setType("face_to_face");
                    planVO1.setClassifyName(planVO.getClassifyName());
                    planVO1.setNumberAppointments(planVO.getNumberAppointments());
                }
                planVO1.setCount(count);
                planVOS1.add(planVO1);
            }

        }
        return planVOS1;
    }

    @Override
    public BookingVO insertClick(Booking booking) {
        Integer planId = booking.getPlanId();
        Long userId = booking.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请选择要预约的咨询师");
        }

        if (ObjectUtil.isEmpty(planId)) {
            throw new BaseException("请选择要预约的班次");
        }
        PlanVO plan1 = bookingMapper.selectPlanId(planId);
        String planDate = plan1.getPlanDate();
        String planTime = plan1.getPlanTime();
        BigDecimal price = plan1.getPrice();
        //获取咨询的类型
        Long classifyId = plan1.getClassifyId();
        PlanDTO planDTO = new PlanDTO();
        planDTO.setPlanDate(planDate);
        planDTO.setUserId(userId);
        planDTO.setPlanTime(planTime);
        //获取当前时间段的排版id
        PlanVO planVO = bookingMapper.selectNumberPeople(planDTO);
        //查看该时间段的可预约的人数
        Integer numberAppointments = planVO.getNumberAppointments();
        //判断id是否重复
        Booking booking1 = bookingMapper.selectClick(booking);
        if (ObjectUtil.isNotEmpty(booking1)) {
            if (booking1.getId() == planVO.getId()) {
                throw new BaseException("该时间段您已预约，不可重复预约");
            }
        }
        Long currentId = BaseContext.getCurrentId();
        booking.setRegularId(currentId);
        booking.setCreateTime(LocalDateTime.now());
        booking.setBookingStatus(1);
        //新增预约记录
        // booking.
        if (ObjectUtil.isEmpty(numberAppointments)) {
            throw new BaseException("该时间段咨询师未开放不能预约");
        }
        int i = bookingMapper.insertClick(booking);
        if (i > 0) {
            if (numberAppointments > 0) {
                Plan plan = new Plan();
                plan.setNumberAppointments(numberAppointments - 1);
                plan.setPlanDate(planDate);
                plan.setUserId(booking.getUserId());
                plan.setPlanTime(planTime);
                //改为有预约
                plan.setDisables(1);
                bookingMapper.updateNumberPeople(plan);
            }
        }
        Long id = booking.getId();
        BookingVO bookingVO = new BookingVO();
        bookingVO.setId(id);
        //预约完生成订单
        Orders orders = new Orders();
        orders.setBookingId(id);
        SimpleDateFormat yyyyMMddHHmmssSSS = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = yyyyMMddHHmmssSSS.format(new Date());
        String ordersNumber = "XL" + format;
        orders.setOrdersNumber(ordersNumber);
        orders.setUserId(userId);
        orders.setRegularId(currentId);
        //未支付
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setCreateTime(LocalDateTime.now());
        System.out.println("订单的价格 = " + price);
        orders.setPrice(price);
        //咨询的类型
        orders.setClassifyId(classifyId);
        //添加订单记录
        ordersMapper.insert(orders);
        Long ordersid = orders.getId();
        OrderVO orderVO = ordersMapper.select(ordersid);
        bookingVO.setStatus(orderVO.getStatus());
        //订单号
        bookingVO.setOrdersNumber(orderVO.getOrdersNumber());
        bookingVO.setOrdersId(orderVO.getId());
        return bookingVO;
    }

    @Override
    public void insertPersonal(List<PsychologicalAppointmentRecords> appointmentRecords) {

        if (appointmentRecords != null && appointmentRecords.size() > 0) {

            appointmentRecords.forEach(psychologicalAppointmentRecords -> psychologicalAppointmentRecords.setCreateTime(LocalDateTime.now()));

            recordsMapper.insert(appointmentRecords);
        }
    }

    @Override
    public BookingVO selectPersonal(Booking booking) {
        if (ObjectUtil.isEmpty(booking)) {
            throw new BaseException("该预约记录不存在");
        }
        Long currentId = BaseContext.getCurrentId();
        booking.setRegularId(currentId);
        BookingVO bookingVO = bookingMapper.selectPersonal(booking);
        //查看出排班的类型
        Integer planId = bookingVO.getPlanId();

        PlanVO plan = bookingMapper.selectPlanId(planId);
        bookingVO.setPlanDate(plan.getPlanDate());
        bookingVO.setPlanTime(plan.getPlanTime());
        bookingVO.setPlanType(plan.getType());
        String avatar = bookingVO.getAvatar();
        File file = fileService.getById(avatar);
        String a = QiNiuConfig.CNAME + "/" + file.getFileKey();

        bookingVO.setA(a);
        bookingVO.setAvatars(file.getId());
        Long id = bookingVO.getId();
        List<PsychologicalAppointmentRecords> personalId = recordsMapper.selectPersonalId(id);
        bookingVO.setPsychologicalAppointmentRecords(personalId);
        return bookingVO;
    }

    @Override
    public PageResult selectPage(BookingDTO bookingDTO) {
        Integer page = bookingDTO.getPage();
        Integer pageSize = bookingDTO.getPageSize();
        if (ObjectUtil.isEmpty(page) && ObjectUtil.isEmpty(pageSize)) {
            throw new BaseException("页码数和每页条数不能为空");
        }
        PageHelper.startPage(page, pageSize);
        Long currentId = BaseContext.getCurrentId();
        bookingDTO.setRegularId(currentId);
        //获取已完成的订单
        bookingDTO.setOrdersStatus(2L);
        List<BookingVO> bookingVO = bookingMapper.selectPage(bookingDTO);
        Page<BookingVO> p = (Page<BookingVO>) bookingVO;
        List<BookingVO> result = p.getResult();
        ArrayList<BookingVO> bookingVOS = new ArrayList<>();
        for (BookingVO vo : result) {
            File file = fileService.getById(vo.getAvatar());
            String a = QiNiuConfig.CNAME + "/" + file.getFileKey();

            BookingVO bookingVO1 = new BookingVO();
            BeanUtils.copyProperties(vo, bookingVO1);
            bookingVO1.setA(a);
            Integer planId = vo.getPlanId();
            //查询出预约的排班信息
            PlanVO plan = bookingMapper.selectPlanId(planId);
            if (ObjectUtil.isEmpty(plan)) {
                throw new BaseException("排班id不存在");
            }
            bookingVO1.setPlanDate(plan.getPlanDate());
            bookingVO1.setPlanTime(plan.getPlanTime());
            //咨询类型
            bookingVO1.setPlanType(plan.getType());
            bookingVO1.setPlanTypeId(plan.getClassifyId());
            //服务的方式  面对面还 语音
            bookingVO1.setType(plan.getServiceMode());
            bookingVO1.setCreateTime(plan.getCreateTime());
            //预约待核销 ，已 核销
            bookingVO1.setBookingStatus(vo.getBookingStatus());
            Long id = vo.getId();
            if (ObjectUtil.isNotEmpty(id)) {
                PsychologicalAppointmentRecords appointmentRecords = recordsMapper.selectBookId(id);
                //查看个人信息是否完善
                if (ObjectUtil.isNotEmpty(appointmentRecords)) {
                    bookingVO1.setPersonalInformation(true);
                } else {
                    bookingVO1.setPersonalInformation(false);
                }
            }
            bookingVOS.add(bookingVO1);
        }
        PageResult pageResult = new PageResult(p.getTotal(), bookingVOS);
        return pageResult;
    }
}
